const { parseString } = require('xml2js');
const { promisify } = require('util');
const { createNodeHelpers } = require('gatsby-node-helpers');

const parse = promisify(parseString);

async function onCreateNode({
  node,
  actions,
  loadNodeContent,
  createNodeId,
  createContentDigest,
}) {
  if (node.internal.mediaType === 'application/xml') {
    console.log('>>> createNodeId :', createNodeId);

    const content = await loadNodeContent(node);
    console.log('plugin:[gatsby-transformer-xml] xml content :', content);
    const nodeContent = await parse(content, {
      explicitRoot: false,
      explicitArray: false,
    });
    // const nodeContent = { name: '张三', age: 20 };
    console.log(
      'plugin:[gatsby-transformer-xml] parsed nodeContent :',
      JSON.stringify(nodeContent, null, 2)
    );

    // 1. 构建数据节点对象 allXMLParsedContent
    const { createNodeFactory } = createNodeHelpers({
      typePrefix: 'XML',
      createNodeId,
      createContentDigest,
    });
    const createNodeObject = createNodeFactory('parsedContent');
    // 数据节点对象
    const nodeObj = createNodeObject({
      id: createNodeId('XML'),
      nodeContent,
    });
    // 创建节点
    const { createNode } = actions;
    console.log(
      'plugin:[gatsby-transformer-xml] createNodeHelpers nodeObj :',
      nodeObj
    );
    createNode(nodeObj);
  }
}

module.exports = { onCreateNode };
